package com.cl.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cl.annotation.IgnoreAuth;
import com.cl.entity.ConfigEntity;
import com.cl.entity.EIException;
import com.cl.service.ConfigService;
import com.cl.utils.R;

/**
 * 文件管理控制器
 */
@RestController
@RequestMapping("file")
public class FileController {

	@Autowired
	private ConfigService configService;

	private static final String FILE_DIRECTORY = "/file/";

	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	@IgnoreAuth
	public R upload(@RequestParam("file") MultipartFile file, String type) throws Exception {
		if (file.isEmpty()) {
			throw new EIException("上传文件不能为空");
		}

		String fileExt = getFileExtension(file.getOriginalFilename());
		File uploadDir = getUploadDirectory();

		String fileName = generateFileName(type, fileExt);
		File dest = new File(uploadDir, fileName);

		file.transferTo(dest);

		if ("1".equals(type)) {
			updateConfigEntity(fileName);
		}

		return R.ok().put("file", fileName);
	}

	/**
	 * 下载文件
	 */
	@RequestMapping("/download")
	@IgnoreAuth
	public ResponseEntity<byte[]> download(@RequestParam String fileName) {
		try {
			File uploadDir = getUploadDirectory();
			File file = new File(uploadDir, fileName);

			if (file.exists()) {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				headers.setContentDispositionFormData("attachment", fileName);
				return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
	}

	private File getUploadDirectory() throws IOException {
		File path = new File(ResourceUtils.getURL("classpath:static").getPath());
		if (!path.exists()) {
			path = new File("");
		}
		File uploadDir = new File(path.getAbsolutePath(), FILE_DIRECTORY);
		if (!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
		return uploadDir;
	}

	private String getFileExtension(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	private String generateFileName(String type, String fileExt) {
		if (StringUtils.isNotBlank(type) && type.contains("_template")) {
			return type + "." + fileExt;
		}
		return new Date().getTime() + "." + fileExt;
	}

	private void updateConfigEntity(String fileName) {
		ConfigEntity configEntity = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
		if (configEntity == null) {
			configEntity = new ConfigEntity();
			configEntity.setName("faceFile");
		}
		configEntity.setValue(fileName);
		configService.insertOrUpdate(configEntity);
	}
}